""" 编写对仓库数据的增删改查 """
import json

from django.http import JsonResponse
from django.db.models import Q
from web.models import Order, Warehouse
from datetime import datetime
import logging

system_logger = logging.getLogger('system_log')


def warehouse_search(request):
    """仓库数据查询"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        system_logger.info("__开始仓库数据查询操作__")
        currentPage = data['currentPage']  # 当前界面
        pageSize = data['pageSize']  # 页面大小
        search = data['search']  # 关键字
        # 数据库中提取数据
        if search != '':
            # 模糊查询
            result_objects = Warehouse.objects.filter(
                (Q(warehouse_name__icontains=search) | Q(address__icontains=search)
                 | Q(commander__icontains=search)) & Q(is_delete=0))
            # 构建结果列表
            output = []
            for result in result_objects:
                data = {
                    'warehouse_id': result.warehouse_id,
                    'warehouse_name': result.warehouse_name,
                    'address': result.address,
                    'commander': result.commander,
                    'state': result.state,
                    'remarks': result.remarks
                }
                output.append(data)

        else:
            # 执行关联查询，并选择相关字段
            result_objects = Warehouse.objects.filter(is_delete=0).values('warehouse_id', 'warehouse_name', 'address',
                                                                          'commander', 'state', 'remarks')
            # 构建结果列表
            output = []
            for result in result_objects:
                data = {
                    'warehouse_id': result["warehouse_id"],
                    'warehouse_name': result["warehouse_name"],
                    'address': result["address"],
                    'commander': result["commander"],
                    'state': result["state"],
                    'remarks': result["remarks"]
                }
                output.append(data)

        # 计算总数
        count = result_objects.count()
        # 计算分页索引
        index_start = pageSize * (currentPage - 1)
        index_end = index_start + pageSize
        if index_start > count:
            system_logger.error("需要查询的仓库信息页面大于订单数量__查询失败")
            return JsonResponse({'code': '1', 'msg': "查询失败，原因是分页参数错误"})
        else:
            data_list = output[index_start: index_end]
            data_json = {'data': data_list, 'total': count}
            if search != '':
                system_logger.info(f"与{search}关键字相关的仓库信息查询操作__成功")
            else:
                system_logger.info("仓库信息查询操作__成功")
            return JsonResponse({'code': '0', 'msg': "查询成功！", 'data': data_json})

    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "数据查询过程出错，具体原因：" + str(e)})
        system_logger.error(f"仓库数据查询过程出错，具体原因：{e}__查询失败")
        return JsonResponse({'code': '1', 'msg': "查询失败！", 'data': "null"})


def warehouse_add(request):
    """仓库新增"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        system_logger.info("__开始新增仓库数据操作__")
        # 创建一个数据对象
        add_data = Warehouse(
            warehouse_name=data['warehouse_name'],
            address=data['address'],
            commander=data['commander'],
            state=data['state'],
            remarks=data['remarks'],
        )
        add_data.save()
        system_logger.info("新增仓库数据操作__成功")
        return JsonResponse({'code': '0', 'msg': "添加成功！", 'data': "null"})

    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "订单添加过程出错，具体原因：" + str(e)})
        system_logger.error(f"新增仓库数据操作过程出错，具体原因：{e}__操作失败")
        return JsonResponse({'code': '1', 'msg': "添加失败！", 'data': "null"})


def warehouse_update(request):
    """仓库信息修改"""
    # 接收前端传递过来的值
    system_logger.info("__开始修改仓库数据操作__")
    data = json.loads(request.body.decode("utf-8"))
    try:

        update_data = Warehouse.objects.get(warehouse_id=data['warehouse_id'])
        update_data.warehouse_name = data['warehouse_name']
        update_data.address = data['address']
        update_data.commander = data['commander']
        update_data.state = data['state']
        update_data.remarks = data['remarks']

        update_data.save()
        system_logger.info("修改仓库数据操作__成功")
        return JsonResponse({'code': '0', 'msg': "修改成功！", 'data': "null"})
    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "订单信息修改过程出错，具体原因：" + str(e)})
        system_logger.error(f"修改仓库数据操作过程出错，具体原因：{e}__操作失败")
        return JsonResponse({'code': '1', 'msg': "修改失败！", 'data': "null"})


def warehouse_delete(request):
    """仓库信息删除"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        system_logger.info(f"__开始删除warehouse_id为{data['warehouse_id']}的仓库数据操作__")
        delete_data = Warehouse.objects.get(warehouse_id=data['warehouse_id'])

        # 查询需要删除的数据，没有删除，只是修改了is_delete和delete_time字段
        delete_data.is_delete = 1
        delete_data.delete_time = datetime.now()
        delete_data.save()
        system_logger.info(f"删除warehouse_id为{data['warehouse_id']}的仓库数据操作__成功")
        return JsonResponse({'code': '0', 'msg': "删除成功！", 'data': "null"})
    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "订单信息删除过程出错，具体原因：" + str(e)})
        system_logger.error(f"删除warehouse_id为{data['warehouse_id']}的仓库数据操作过程出错，具体原因：{e}__操作失败")
        return JsonResponse({'code': '1', 'msg': "删除失败！", 'data': "null"})

